package com.generalbackend.common.dingtalk.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.generalbackend.common.dingtalk.entity.DingRequestBody;
import com.generalbackend.common.dingtalk.entity.Markdown;
import com.generalbackend.common.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;

/**
 * @author tim.xie
 * @date 2021/12/24 16:35
 */
@Slf4j
public class DingDingRobotUtil {

    /**
     * 发送钉钉消息
     * @param dingRequestBody
     * @param token
     * @param sign
     * @return
     */
    public static String sendMessage(DingRequestBody dingRequestBody, String token, String sign) {
        Long timestamp = System.currentTimeMillis();
        try {
            sign = getSign(timestamp, sign);
        } catch (Exception e) {
            log.error("加签失败", e);
            return "加签失败";
        }
        String url = "https://oapi.dingtalk.com/robot/send?access_token=" + token + "&sign=" + sign + "&timestamp=" + timestamp;
        return HttpClientUtil.doHttpPost(url, JSON.parseObject(JSONObject.toJSONString(dingRequestBody)));
    }

    /**
     *
     * @param timestamp
     *            当前时间戳，单位是毫秒
     * @param secret
     *            密钥
     * @return
     * @throws Exception
     */
    private static String getSign(Long timestamp, String secret) throws Exception {
        String stringToSign = timestamp + "\n" + secret;
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
        byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
        String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
        return sign;
    }

    public static void main(String[] args) throws Exception {

        String test = "http%3A%2F%2F192.168.152.1%3A8081%2Fapi%2Flicense%2FdbDat%2Fdownload%3Fid%3D3021710542503936";
        String uri = "dingtalk://dingtalkclient/page/link?url=" + test + "&pc_slide=false";

        Long timestamp = System.currentTimeMillis();
        String sign = getSign(timestamp, "SEC8e5537a3138eab5e73e0a84094e59e766f37edb2bd2ef71d1345da34e01eb092");
        String url = "https://oapi.dingtalk.com/robot/send?access_token=4e61c2fd8a97f7a38dada0d9bd45fd576a5cefd959ab66070268ef93e4ab42d0&sign=" + sign + "&timestamp=" + timestamp;
        DingRequestBody dingRequestBody = null;

        /**
         * 链接
         */
//        dingRequestBody = DingRequestBody.buildLink(Link.builder()
//                .title("时代的火车向前开")
//                .messageUrl("https://gitee.com/XieYiXuan_admin")
//                .text("这个即将发布的新版本，创始人xx称它为红树林。而在此之前，每当面临重大升级，产品经理们都会取一个应景的代号，这一次，为什么是红树林")
//                .picUrl("https://api.j4u.ink/proxy/redirect/moyu/calendar/20230413.png").build());

        /**
         * 卡片
         */
//        dingRequestBody = DingRequestBody.buildActionCard(ActionCard.buildOverallJumpActionCard("乔布斯","![screenshot](https://api.j4u.ink/proxy/redirect/moyu/calendar/20230413.png) \n" +
//                " ### 乔布斯 20 年前想打造的苹果咖啡厅 \n" +
//                " Apple Store 的设计正从原来满满的科技感走向生活化，而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划", "0","阅读全文",uri));

        dingRequestBody = DingRequestBody.buildMarkDown(Markdown.builder().title("title").text("![screenshot](https://api.j4u.ink/proxy/redirect/moyu/calendar/20230413.png)").build());
        String s = HttpClientUtil.doHttpPost(url, JSON.parseObject(JSONObject.toJSONString(dingRequestBody)));
        System.out.println(s);
        System.out.println(JSONObject.toJSONString(dingRequestBody));
    }
}
